<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;

class UserCoupon extends Base
{
    protected $table = 'user_coupon';
    protected $primaryKey = 'user_coupon_id';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 用户优惠券-创建/更新
     *
     * @param array $data 数据
     * @param string $type 操作类型 默认 insert=创建，update=更新，increment=累加，decrement=减少
     * @return bool
     * */
    public function updateOrInsertUserCoupon($data, $type = 'insert')
    {
        $timestamp = time();

        switch ($type) {
            case 'insert':
                $ret = DB::table($this->table)->insertGetId([
                    'user_id' => $data['user_id'],
                    'prop_config_id' => $data['prop_config_id'],
                    'num' => $data['num'],
                    'used_at' => $data['used_at'],
                    'created_at' => $timestamp,
                    'updated_at' => $timestamp
                ]);
                break;
            case 'update':
                $ret = DB::table($this->table)->where([$this->primaryKey => $data[$this->primaryKey]])->update(['num' => $data['num'], 'updated_at' => $timestamp]);
                break;
            case 'increment':
                $ret = DB::table($this->table)->where([$this->primaryKey => $data[$this->primaryKey]])->increment('num', $data['num'], ['updated_at' => $timestamp]);
                break;
            case 'decrement':
                $ret = DB::table($this->table)->where([$this->primaryKey => $data[$this->primaryKey]])->decrement('num', $data['num'], ['updated_at' => $timestamp]);
                break;
            default:
                $ret = false;
                break;
        }

        return $ret;
    }

    /**
     * 查询用户优惠券
     *
     * @param int $userId 用户ID
     * @param int $type 优惠券类型
     * @return array
     * */
    public function getUserCoupon($userId, $type)
    {
        $db = DB::table($this->table)
            ->where([
                ['user_id', '=', $userId],
                ['type', '=', $type],
                ['used_at', '=', 0]
            ])->orWhere(['user_id' => $userId])
            ->where(['type' => $type])
            ->where('used_at', '>', time());

        $data = $db->first();
        return self::objToArray($data);
    }
}